package IPLimit;

require 5;
use Carp;

BEGIN 
{
	use TWM;
	use Data::Dumper;
	use Bandwidth;
	use IPC::ShareLite;
	use Storable qw( freeze thaw );
}


sub new
{
	my $self = {
		this_module_code => 'http_ip_limit',
		http_bandwidth_code => 'http_bandwidth',
		http_logging_code => 'http_logging'
	};
	return bless $self;
}

sub DESTROY	{
	my $self = shift;
	delete $self->{$_} for (keys %$self);
	undef(%$self);
	undef $self;
}


sub load_total
{
	my $self = shift;
	my $shared = IPC::ShareLite->new(
	        -key     => 1975,
        	-create  => 'yes',
       		 -destroy => 'no'
	    ) or die $!;
	my $data_shared = thaw($shared->fetch()||undef);
	return $data_shared->{total}||{};
}


#####################################################
# returns list of blocked ip
#####################################################
sub get_blocked_list
{
	my $self = shift;
	populateCfromConfig($self->{http_bandwidth_code}) if (!$C->{$self->{http_bandwidth_code}});
	my $blocked = readModuleConfigFile($C->{$self->{http_bandwidth_code}}->{classes_config}, $self->{http_bandwidth_code});
	if (ref $blocked->{acl} eq 'HASH' && $blocked->{acl}->{name} eq $cm{blocked_ip_list})
	{
		$content = $blocked->{acl}->{content};
	}
	else
	{
		$content = $blocked->{acl}->{$cm{blocked_ip_list}}->{content};
	}
	return undef if ref $content eq 'HASH' || !$content;
	my @blockedlist = split /\n/, $content;
	return \@blockedlist;
}

sub saveBlockedList
{
	my ($self, $blocked_ip_list) = (shift, shift);
	my $content = '';
	$content .= "$_\n" for (keys %$blocked_ip_list);
	populateCfromConfig($self->{http_bandwidth_code}) if (!exists $C->{$self->{http_bandwidth_code}});
	my $blocked = readModuleConfigFile($C->{$self->{http_bandwidth_code}}->{classes_config}, $self->{http_bandwidth_code});
	my $acl = {
		'blocked' => 1
		, 'content' => $content
		, 'description' => 'http ip limit module acl class'
		, 'label' =>'HTTP ip limit'
		, 'readonly' =>1
		, 'type' => 'src'
		, 'name' => $cm{blocked_ip_list}
	};
	exists($blocked->{acl}->{$cm{blocked_ip_list}}) ? $blocked->{acl}->{$cm{blocked_ip_list}} = $acl : $blocked->{acl} = $acl;
	toDebugLog("Saving blocked_ip_list.\n$content");
	my $bandWidth = Bandwidth->new();
	$bandWidth->saveClass($blocked);
}

return 1;
{}
